package com.uni.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.ParseException;

/**
 * 唯一ID生成工具类
 */
@Slf4j
@Component
public class IdGeneratorSnowflake {

    private long workerId = 0; //工作机器ID
    private long datacenterId = 1; //数据中心ID
    private Snowflake snowflake =
            IdUtil.createSnowflake(workerId, datacenterId); //hutool

    @PostConstruct //JSR-250的规范，当bean创建并完成注入的时候，会后置执行@PostConstruct修饰的方法
    public void init(){

        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的workerId: {}",workerId);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("当前机器的workerId获取失败",e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized long snowflakeId(){
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId, long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }

    public static void main(String[] args) throws ParseException {
        //System.out.println(new IdGeneratorSnowflake().snowflakeId());
    }
}